// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package script_cmd

import (
	_ "embed"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

//go:embed demo.py
var pythonTpl string

//go:embed demo.js
var nodeJsTpl string

var genCmd = &cobra.Command{
	Use: "gen",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [dest file]")
		}
		fileName := args[0]
		if strings.HasSuffix(fileName, ".py") || strings.HasSuffix(fileName, ".js") {
			//do nothing
		} else {
			return fmt.Errorf("only support .py(python) and .js(nodejs)")
		}
		_, err := os.Stat(fileName)
		if err == nil { //文件存在
			return fmt.Errorf("dest file exist")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		fileName := args[0]
		content := ""
		if strings.HasSuffix(fileName, ".py") {
			content = strings.ReplaceAll(pythonTpl, "\r", "")
		} else if strings.HasSuffix(fileName, ".js") {
			content = strings.ReplaceAll(nodeJsTpl, "\r", "")
		}
		err := os.WriteFile(fileName, []byte(content), 0755)
		if err != nil {
			return err
		}
		fmt.Println("gen code success")
		return nil
	},
}
